<template>  
    <div class="user-favorites">
      <!-- 标题部分 -->
      <div class="favorites-tabs">
        <div 
          :class="['tab', { active: activeTab === 'Codex' }]" 
          @click="switchTab('Codex')"
        >
          收藏青铜图鉴
        </div>
        <div 
          :class="['tab', { active: activeTab === '3D' }]" 
          @click="switchTab('3D')"
        >
          收藏三维模型
        </div>
      </div>
  
      <!-- 内容部分 -->
      <div class="favorites-content">
        <transition-group name="fade" tag="div">
          <!-- 收藏青铜图鉴 -->
          <div v-if="activeTab === 'Codex'" key="codex" class="artifacts-grid">
            <div 
              v-for="artifact in artifacts" 
              :key="artifact.id" 
              class="artifact-card"
            >
              <div class="artifact-image">
                <img 
                  :src="getImageUrl(artifact.id, artifact.class)" 
                  :alt="artifact.name"
                >
                <!-- 取消收藏图标按钮 -->
                <button 
                  class="unfavorite-button" 
                  @click.stop="unfavoriteArtifact(artifact.id)"
                  :disabled="isProcessingFavorites"
                  aria-label="取消收藏"
                >
                  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" class="icon">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                          d="M6 18L18 6M6 6l12 12"/>
                  </svg>
                </button>
              </div>
              <div class="artifact-info">
                <h3>{{ artifact.name }}</h3>
                <p><strong>年代:</strong> {{ artifact.era }}</p>
                <p><strong>收藏地点:</strong> {{ artifact.current_location || '未知' }}</p>
                <p><strong>挖掘地点:</strong> {{ artifact.excavation_location }}</p>
              </div>
            </div>
          </div>
  
          <!-- 收藏三维模型 -->
          <div v-if="activeTab === '3D'" key="3d" class="artifacts-grid">
            <div 
              v-for="(model, index) in favoriteModels" 
              :key="model.id" 
              class="artifact-card"
            >
              <div class="artifact-image" @click="showModel(index)">
                <img 
                  :src="model.thumbnail" 
                  :alt="model.name"
                >
                <!-- 取消收藏图标按钮 -->
                <button 
                  class="unfavorite-button" 
                  @click.stop="unfavoriteModel(model.id)"
                  :disabled="isProcessingFavorites"
                  aria-label="取消收藏"
                >
                  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" class="icon">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                          d="M6 18L18 6M6 6l12 12"/>
                  </svg>
                </button>
              </div>
              <div class="artifact-info">
                <h3>{{ model.name }}</h3>
                <p>{{ model.description }}</p>
              </div>
            </div>
          </div>
        </transition-group>
      </div>
  
      <!-- 模型查看器 -->
      <div v-if="showModelViewer" class="model-viewer-overlay">
        <div class="model-viewer">
          <div class="model-viewer-header">
            <h2>{{ currentModel.name }}</h2>
            <button @click="closeModelViewer" class="close-button">
              <i class="fas fa-times"></i>
            </button>
          </div>
          <div id="model-container"></div>
          <div v-if="loading" class="loading-bar">
            <div class="progress" :style="{ width: loadingProgress + '%' }"></div>
          </div>
          <div class="model-description">
            <p>{{ currentModel.description }}</p>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  import { BASE_URL } from '@/config.js';
  import { models } from './modelsData.js'; // 导入模型数据
  import * as THREE from 'three';
  import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
  import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
  
  export default {
    name: 'UserFavorites',
    data() {
      return {
        userId: null,
        activeTab: 'Codex', // 默认显示 收藏青铜图鉴
        artifacts: [],
        favoriteModels: [], // 收藏的模型列表
        isProcessingFavorites: false,
        classMapping: {
          "gui": "簋", "hu": "壺", "yan": "甗", "you": "卣", "jue": "爵",
          "zhong": "鐘", "gu": "觚", "zhi": "觶", "ding": "鼎", "li": "鬲",
          "yi": "匜", "zun": "尊"
        },
        // 三维模型查看器相关
        showModelViewer: false,
        currentModel: null,
        loading: false,
        loadingProgress: 0,
      };
    },
    methods: {
      switchTab(tab) {
        this.activeTab = tab;
        if (tab === 'Codex') {
          this.fetchFavoritedArtifacts();
        } else if (tab === '3D') {
          this.fetchFavoritedModels();
        }
      },
      getImageUrl(id, artifactClass) {
        const folder = Object.keys(this.classMapping).find(key => this.classMapping[key] === artifactClass);
        return `/images/${folder}/${id}`;
      },
      async fetchFavoritedArtifacts() {
        try {
          const response = await axios.get(`${BASE_URL}/api/users/${this.userId}/artifact-favorites-details`);
          this.artifacts = response.data;
        } catch (error) {
          console.error('获取收藏的文物详情失败:', error);
        }
      },
      async unfavoriteArtifact(artifactId) {
        this.isProcessingFavorites = true;
        try {
          const response = await axios.delete(`${BASE_URL}/api/artifacts/${artifactId}/favorite`, {
            data: { userId: this.userId }
          });
  
          if (response.status === 200) {
            // 使用动画移除文物
            this.artifacts = this.artifacts.filter(artifact => artifact.id !== artifactId);
          }
        } catch (error) {
          console.error('取消收藏失败:', error);
          alert('取消收藏失败，请稍后再试！');
        } finally {
          this.isProcessingFavorites = false;
        }
      },
      async fetchFavoritedModels() {
        try {
          const response = await axios.get(`${BASE_URL}/api/users/${this.userId}/model-favorites`);
          const favoriteModelIds = response.data.map(item => item.model_id);
          this.favoriteModels = models.filter(model => favoriteModelIds.includes(model.id));
        } catch (error) {
          console.error('获取收藏的模型详情失败:', error);
        }
      },
      async unfavoriteModel(modelId) {
        this.isProcessingFavorites = true;
        try {
          const response = await axios.delete(`${BASE_URL}/api/models/${modelId}/favorite`, {
            data: { userId: this.userId }
          });
  
          if (response.status === 200) {
            // 使用动画移除模型
            this.favoriteModels = this.favoriteModels.filter(model => model.id !== modelId);
          }
        } catch (error) {
          console.error('取消收藏失败:', error);
          alert('取消收藏失败，请稍后再试！');
        } finally {
          this.isProcessingFavorites = false;
        }
      },
      // 显示模型查看器
      showModel(index) {
        this.currentModel = this.favoriteModels[index];
        this.showModelViewer = true;
        this.loading = true;
        this.loadingProgress = 0;
        this.$nextTick(() => {
          this.initThreeJS();
        });
      },
      // 关闭模型查看器
      closeModelViewer() {
        this.showModelViewer = false;
        this.currentModel = null;
        if (this.renderer) {
          this.renderer.dispose();
        }
      },
      // 初始化 Three.js 场景
      initThreeJS() {
        const container = document.getElementById('model-container');
        const width = container.clientWidth;
        const height = container.clientHeight;
  
        const scene = new THREE.Scene();
        scene.background = new THREE.Color(0x000000);
  
        const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
        const { x, y, z } = this.currentModel.cameraPosition;
        camera.position.set(x, y, z);
  
        const renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize(width, height);
        container.appendChild(renderer.domElement);
        this.renderer = renderer;
  
        const controls = new OrbitControls(camera, renderer.domElement);
        controls.enableDamping = true;
        controls.dampingFactor = 0.25;
        controls.screenSpacePanning = false;
        controls.maxPolarAngle = Math.PI / 2;
  
        const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
        scene.add(ambientLight);
  
        const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
        directionalLight.position.set(5, 10, 7.5);
        scene.add(directionalLight);
  
        const loader = new GLTFLoader();
        loader.load(
          this.currentModel.modelPath,
          (gltf) => {
            const model = gltf.scene;
  
            // 计算模型的边界框
            const box = new THREE.Box3().setFromObject(model);
            const center = box.getCenter(new THREE.Vector3());
  
            // 创建一个组来包含模型
            const group = new THREE.Group();
            group.add(model);
  
            // 将模型移动到组的中心
            model.position.sub(center);
  
            // 设置组的缩放和位置
            const { x: sx, y: sy, z: sz } = this.currentModel.modelScale;
            group.scale.set(sx, sy, sz);
  
            const { x: px, y: py, z: pz } = this.currentModel.modelPosition;
            group.position.set(px, py, pz);
  
            // 将组添加到场景
            scene.add(group);
  
            const rotationSpeed = this.currentModel.rotationSpeed;
  
            const animate = () => {
              if (!this.showModelViewer) return; // 如果已关闭查看器，停止动画
              requestAnimationFrame(animate);
              group.rotation.y += rotationSpeed;
              controls.update();
              renderer.render(scene, camera);
            };
            animate();
  
            this.loading = false;
          },
          (xhr) => {
            this.loadingProgress = Math.round((xhr.loaded / xhr.total) * 100);
          },
          (error) => {
            console.error('加载模型出错', error);
            this.loading = false;
          }
        );
  
        window.addEventListener('resize', this.onWindowResize);
      },
      // 窗口调整大小事件
      onWindowResize() {
        const container = document.getElementById('model-container');
        if (!container || !this.renderer) return;
        const width = container.clientWidth;
        const height = container.clientHeight;
        this.renderer.setSize(width, height);
      },
      checkLoginStatus() {
        const userId = localStorage.getItem('userId');
        if (userId) {
          this.userId = userId;
          if (this.activeTab === 'Codex') {
            this.fetchFavoritedArtifacts();
          } else if (this.activeTab === '3D') {
            this.fetchFavoritedModels();
          }
        } else {
          alert('请先登录！');
          // 可以跳转到登录页面，或者根据需求处理
        }
      }
    },
    mounted() {
      this.checkLoginStatus();
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.onWindowResize);
      if (this.renderer) {
        this.renderer.dispose();
      }
    }
  };
  </script>
  
  <style scoped>
  .user-favorites {
background-image: url('@/assets/s5.jpg'); 
background-repeat: no-repeat; /* 背景图不重复 */
background-size: cover; /* 背景图覆盖整个区域 */
background-position: center; /* 背景图居中 */
background-attachment: fixed; /* 背景图固定 */
    padding: 20px;
    min-height: 100vh;
    /* background-color: #f5f0e6; 背景色 */
  }
  
  .favorites-tabs {
    display: flex;
    justify-content: center;
    margin-bottom: 30px;
    position: relative;
    margin-top: 52px;
  }
  
  .tab {
    margin: 0 40px;
    padding: 10px 20px;
    cursor: pointer;
    font-size: 1.8em;
    position: relative;
    transition: color 0.3s;
    font-weight: bold;
    color: #8b4513;
  }
  
  .tab::after {
    content: '';
    position: absolute;
    left: 50%;
    bottom: -5px;
    transform: translateX(-50%);
    width: 0%;
    height: 3px;
    background-color: #cd853f;
    transition: width 0.3s;
  }
  
  .tab:hover {
    color: #cd853f;
  }
  
  .tab:hover::after {
    width: 100%;
  }
  
  .tab.active {
    color: #cd853f;
  }
  
  .tab.active::after {
    width: 100%;
  }
  
  .favorites-content {
    /* 内容区域样式 */
  }
  
  .artifacts-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 25px;
  }
  
  .artifact-card {
    border: 3px solid #cd853f;
    padding: 15px;
    background: #fffaf0;
    border-radius: 15px;
    box-shadow: 0 8px 16px rgba(0,0,0,0.1);
    display: flex;
    flex-direction: column;
    align-items: center;
    transition: all 0.4s ease;
    overflow: hidden;
    position: relative; /* 用于定位取消收藏按钮 */
  }
  
  .artifact-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 12px 24px rgba(0,0,0,0.2);
  }
  
  .artifact-card .artifact-image {
    width: 100%;
    height: 180px;
    overflow: hidden;
    border-radius: 10px;
    position: relative;
    cursor: pointer;
  }
  
  .artifact-card .artifact-image img {
    width: 100%;
    height: 100%;
    object-fit: contain;
    display: block;
  }
  
  .unfavorite-button {
    position: absolute;
    top: 10px;
    right: 10px;
    background-color: rgba(231, 76, 60, 0.8);
    color: #fff;
    border: none;
    padding: 6px;
    border-radius: 50%;
    cursor: pointer;
    font-size: 1em;
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s, background-color 0.3s;
  }
  
  .artifact-card:hover .unfavorite-button {
    opacity: 1;
  }
  
  .unfavorite-button:hover {
    background-color: rgba(192, 57, 43, 0.9);
  }
  
  .icon {
    width: 16px;
    height: 16px;
  }
  
  .artifact-info {
    padding: 15px;
    text-align: center;
  }
  
  .artifact-card h3 {
    margin-top: 15px;
    margin-bottom: 10px;
    color: #8b4513;
    font-size: 1.3em;
  }
  
  .artifact-card p {
    margin: 8px 0;
    color: #666;
    font-size: 0.95em;
  }
  
  .fade-enter-active, .fade-leave-active {
    transition: all 0.5s;
  }
  
  .fade-enter, .fade-leave-to {
    opacity: 0;
    transform: translateY(-10px);
  }
  
  /* 模型查看器样式 */
  .model-viewer-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
  }
  
  .model-viewer {
    background-color: #000000;
    width: 80%;
    height: 80%;
    border-radius: 20px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    position: relative;
    animation: slideUp 0.5s ease-out;
  }
  
  @keyframes slideUp {
    from {
      transform: translateY(50%);
    }
    to {
      transform: translateY(0%);
    }
  }
  
  .model-viewer-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 20px;
    background-color: rgba(255, 255, 255, 0.1);
  }
  
  .model-viewer-header h2 {
    color: #fffaf0;
  }
  
  .close-button {
    background-color: transparent;
    color: white;
    border: none;
    font-size: 24px;
    cursor: pointer;
  }
  
  #model-container {
    flex-grow: 1;
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
  
  .loading-bar {
    width: 100%;
    height: 5px;
    background-color: #333;
    overflow: hidden;
  }
  
  .progress {
    height: 100%;
    background-color: #4caf50;
    transition: width 0.3s ease;
  }
  
  .model-description {
    color: white;
    padding: 20px;
    text-align: center;
  }
  
  </style>
  